from django.shortcuts import render, get_object_or_404
from .models import Post

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from .forms import EmailPostForm

def post_list(request):
    object_list = Post.objects.filter(status="draft")
    paginator = Paginator(object_list, 2)    #每页呈现1条
    page = request.GET.get('page')          #如果以get方式请求，则获得当前页的页码

    try:
        current_page = paginator.page(page)     #创建当前页对象
        posts = current_page.object_list      #从当前页对象的object_list属性得到内容列表
    except PageNotAnInteger:
        current_page = paginator.page(1)
        posts = current_page.object_list
    except EmptyPage:
        current_page = paginator.page(paginator.num_pages)
        posts = current_page.object_list

    return render(request, 'blog/post/list.html', {'posts': posts, "page": current_page})

def post_detail(request, post_id):
    #post = get_object_or_404(Post, id=post_id)
    post = get_object_or_404(Post, slug=post, status="draft", published__year=year, published__month=month, published__day=day)
    return render(request, 'blog/post/detail.html', {"post":post})

def post_share(request,post_id):
    post = get_object_or_404(Post,id=post_id,status="draft")
    if request.method == 'GET':
        form = EmailPostForm()

    if request.method == 'POST':
        form = EmailPostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data

    return render(request,'blog/post/share.html',{'post':post,"form":form},)
